<script setup lang="ts">
import CustomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import PageSkeleton from './components/PageSkeleton.vue'
import { getAdvertisement, getFrontCategory, getHotRecommend } from '@/services/home'
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'

// 首页轮播图
const homeBanner = ref<BannerItem[]>([])
/** 获取首页轮播图数据 */
const getHomeBanner = async () => {
  const res = await getAdvertisement()
  if (res.code !== '1') return uni.showToast({ title: res.msg, icon: 'error' })
  homeBanner.value = res.result
}

// 首页分类
const frontCategory = ref<CategoryItem[]>([])
/**获取首页分类数据 */
const getCategory = async () => {
  const res = await getFrontCategory()
  if (res.code !== '1') return uni.showToast({ title: res.msg, icon: 'error' })
  frontCategory.value = res.result
}

// 首页热门推荐
const hotRecommend = ref<HotItem[]>([])
/** 获取首页热门推荐数据 */
const getHotData = async () => {
  const res = await getHotRecommend()
  if (res.code !== '1') return uni.showToast({ title: res.msg, icon: 'error' })
  hotRecommend.value = res.result
}

// 猜你喜欢
import {
  getGuessData,
  isTriggered,
  isFinite,
  guessList,
  onScrollToLower,
  onRefresh,
} from '@/composables/useGuessYouLink'

// 滚动视图下拉刷新被触发事件
const onRefresherrefresh = () => {
  onRefresh([getHomeBanner(), getCategory(), getHotData(), getGuessData()])
}

// 是否显示骨架屏
const isLoading = ref<boolean>(false)

onLoad(() => {
  isLoading.value = true
  Promise.all([getHomeBanner(), getCategory(), getHotData(), getGuessData()]).finally(() => {
    isLoading.value = false
  })
})
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar />
  <!-- 滚动容器 -->
  <scroll-view
    class="scroll-content"
    refresher-enabled
    scroll-y
    :refresher-triggered="isTriggered"
    @scrolltolower="onScrollToLower"
    @refresherrefresh="onRefresherrefresh"
  >
    <!-- 骨架屏 -->
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <!-- 自定义轮播图 -->
      <xtx-Swiper :list="homeBanner" />
      <!-- 分类面板 -->
      <CategoryPanel :list="frontCategory" />
      <!-- 热门推荐 -->
      <HotPanel :list="hotRecommend" />
      <!-- 猜你喜欢 -->
      <xtx-Guess :list="guessList" title="猜你喜欢" :finish="isFinite.value" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
  .scroll-content {
    flex: 1;
  }
}
</style>
